package com.luckberry.murder.service.impl;

import com.alibaba.fastjson.JSON;
import com.luckberry.murder.entity.good.Good;
import com.luckberry.murder.entity.good.Order;
import com.luckberry.murder.mapper.GoodMapper;
import com.luckberry.murder.mapper.OrderMapper;
import com.luckberry.murder.mapper.UserMapper;
import com.luckberry.murder.mapper.VIPMapper;
import com.luckberry.murder.service.OrderService;
import com.luckberry.murder.util.JSONUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper mapper;
    @Resource
    private GoodMapper goodMapper;
    @Resource
    private VIPMapper vipMapper;

    @Override
    public List<Order> getOrders() {
        return mapper.getOrders();
    }

    @Override
    public List<Order> getOrdersByUid(int uid) {
        return mapper.getOrdersByUser(uid);
    }

    @Override
    public Order getOrder(int oid) {
        return mapper.getOrder(oid);
    }

    @Override
    public boolean addOrder(Order order) {
        if (vipMapper.getVIP(order.getUid()) != null) order.setPrice(order.getPrice() * 0.9);
        if (order.getType().equals("good")) {
            Good good = JSON.parseObject(order.getContent(), Good.class);
            good.setCount(Math.max(good.getCount() - order.getCount(), 0));
            goodMapper.editGood(good);
        }
        return mapper.addOrder(order) == 1;
    }

    @Override
    public boolean deleteOrder(int oid) {
        Order order = mapper.getOrder(oid);
        if (order == null) return false;
        if (order.getType().equals("good")) {
            Good good = JSON.parseObject(order.getContent(), Good.class);
            good.setCount(good.getCount() + order.getCount());
            goodMapper.editGood(good);
        }
        return mapper.deleteOrder(oid) == 1;
    }

    @Override
    public boolean editOrder(Order order) {
        return mapper.editOrder(order) == 1;
    }
}
